import { Button, Form, Input, Card, Select, Radio, Upload, message } from 'antd';
import React, { useState, useEffect } from 'react';
import { getChannels, pubulishArticle, editArticle, getArticleDetail } from '../../api/article'
import { PlusOutlined } from '@ant-design/icons'
import { useSearchParams } from 'react-router-dom'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useNavigate } from 'react-router-dom';
const { Option } = Select;
const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 30,
  },
};


const Publish = () => {
  const navigate = useNavigate()
  const [params] = useSearchParams()
  const id = params.get('id')
  const [selectData, setSelectData] = useState([])
  const [channelId, setChannelId] = useState('')
  // 存放上传图片的列表
  const [fileList, setFileList] = useState([])
  const [flag, setFlag] = useState('发布')
  // 切换图片
  const [imgCount, setImageCount] = useState(1)
  const onUploadChange = ({ fileList }) => {
    const formatList = fileList.map(file => {
      // 上传完毕 做数据处理
      if (file.response) {
        return {
          url: file.response.data.url
        }
      }
      // 否则在上传中时，不做处理
      return file
    })
    setFileList(formatList)
  }
  const radioChange = (e) => {
    // 这里要使用e.target.value做判断
    const rawValue = e.target.value
    setImageCount(rawValue)
    // // 无图模式
    // if (cacheImgList.current.length === 0) {
    //   return false
    // }
    // 单图模式
    if (rawValue === 1) {
      // setFileList([img])
      // 多图模式
    } else if (rawValue === 3) {
    }
  }

  const onFinish = async (values) => {
    console.log(values);
    // 数据的二次处理 重点是处理cover字段
    const { channel_id, content, title, type } = values
    // 判断type fileList 是匹配的才能正常提交
    const params = {
      channel_id,
      content,
      title,
      type,
      cover: {
        type: type,
        images: fileList.map(item => item.url)
      }
    }
    if (id) {
      await editArticle(id, params)
    } else {
      await pubulishArticle(params)
    }
    navigate('/index/article')
    message.success(flag + '成功！')
  };
  const [form] = Form.useForm()
  const loadDetail = async (id) => {
    const { data } = await getArticleDetail(id)
    // 表单数据回填
    form.setFieldsValue({ ...data, type: data.cover.type })
    // 回填upload
    const formatImgList = data.cover.images.map(url => ({ url }))
    setFileList(formatImgList)
    // 图片type
    setImageCount(data.cover.type)
  }
  useEffect(() => {
    if (id) {
      setFlag('修改')
      loadDetail(id)
    }
  }, [id])
  const handleChange = (value, opt) => {
    console.log(`selected ${opt}`);
    setChannelId(opt)
  };
  const getChannelsData = async () => {
    const res = await getChannels()
    setSelectData(res.data.channels)
  }
  useEffect(() => {
    getChannelsData()
  }, []);
  return (
    <div style={{ width: '100%' }}>
      <Card style={{ width: 600, margin: '0 auto' }}>
        <Form name="nest-messages" form={form} onFinish={onFinish} initialValues={{ type: 1 }}>
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '标题不能为空!'
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '请选择频道!'
              },
            ]}
          >
            <Select placeholder="请选择频道">
              {
                selectData.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)
              }
            </Select>
          </Form.Item>
          <Form.Item label="封面" style={{ marginLeft: 12 }}>
            <Form.Item name="type">
              <Radio.Group onChange={radioChange}>
                <Radio value={1} >单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            <Upload
              name="image"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList
              fileList={fileList}
              action="http://geek.itheima.net/v1_0/upload"
              onChange={onUploadChange}
            >
              <div style={{ marginTop: 8 }}>
                <PlusOutlined />
              </div>
            </Upload>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill theme="snow" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginLeft: 52, width: '300px' }}>
              {flag}文章
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};
export default Publish;